package cn.tedu.order.service;

import cn.tedu.order.entity.AccountMessage;
import cn.tedu.order.entity.Order;
import cn.tedu.order.entity.TxInfo;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.UUID;

/**
 * @author Amos
 * @date 2022/4/23
 */

// 注解会自动设置成监听器，开始监听事务消息的发送
@RocketMQTransactionListener
@Service
@Slf4j
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private RocketMQTemplate t;
    @Autowired
    private TxMapper txMapper;

    @Override
    public void create(Order order) {
        // 准备消息对象
        // 1.xid 2.AccountMessage 3.json(支持异构系统之间的信息传递，都能处理json) 4. spring通用消息
        String xid = UUID.randomUUID().toString().replace("-", "");
        AccountMessage am = new AccountMessage(
                order.getUserId(), order.getMoney(), xid);
        String json = JsonUtil.to(am);
        Message<String> msg = MessageBuilder.withPayload(json).build();

        // 发送事务消息
        // "orderTopic:Tag3"
//        t.sendMessageInTransaction("orderTopic", msg, 传递给监听器的业务数据参数);
        t.sendMessageInTransaction("orderTopic", msg, order);
    }

    public void doCreate(Order order) {
        // 远程调用"全局唯一id发号器"，获得订单id
        Map<String, String> map = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(map.get("data"));

        order.setId(orderId);
        orderMapper.create(order);

        // 这个例子中，不再调用库存，只有账户，订单两个模块参与
        // 因为order模块通过rocketmq异步调用account，所以这里不再通过feign远程account模块
        // 所以注释掉了这两个feign的调用
//        // 远程调用库存，减少库存
//        storageClient.decrease(order.getProductId(), order.getCount());
//        // 远程调用账户，扣减金额
//        accountClient.decrease(order.getUserId(), order.getMoney());
    }

    // 执行本地事务
    @Transactional
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        // 参数：1. 消息对象msg 2. 传递到监听器的业务数据参数 Order对象
        // 对应上文中create方法的t.sendMessageInTransaction("orderTopic", msg, order);
        // 消息： userId, money, xid

        RocketMQLocalTransactionState state; // 用来返回
        int status; // 用来存储到数据库

        try {
            Order order = (Order) o;
            doCreate(order);
            state = RocketMQLocalTransactionState.COMMIT;
            status = 0;
        } catch (Exception e) {
            log.error("创建订单失败", e);
            state = RocketMQLocalTransactionState.ROLLBACK;
            status = 1;
        }
        // 从 message 取出json：{userId:xx, money:xx, xid:xx}
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");

        // 存储状态
        txMapper.insert(new TxInfo(xid, status, System.currentTimeMillis()));
        return state;
    }

    // 处理 rocketmq 事务状态回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 1.xid 2. 查询事务状态 3. 返回
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");

        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo == null) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()) {
            case 0:
                return RocketMQLocalTransactionState.COMMIT;
            case 1:
                return RocketMQLocalTransactionState.ROLLBACK;
            default:
                return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
